import os
import random  # 导入random模块以生成随机数
import numpy as np
import cv2
from sklearn.cluster import KMeans
from flask import Flask, render_template, request, jsonify
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads/'

def generate_random_colors():
    colors = []
    for _ in range(5):
        r = random.randint(0, 255)
        g = random.randint(0, 255)  # 补全绿色分量
        b = random.randint(0, 255)  # 补全蓝色分量
        color = '#%02x%02x%02x' % (r, g, b)
        colors.append(color)
    return colors

def extract_colors(image, n_colors=5):
    image = image.reshape(-1, 3)
    kmeans = KMeans(n_clusters=n_colors, n_init='auto')
    kmeans.fit(image)
    return kmeans.cluster_centers_

@app.route('/')
def home():
    return render_template('home.html')

@app.route('/random_palette', methods=['POST'])
def random_palette():
    colors = generate_random_colors()
    return jsonify(colors)

@app.route('/upload_image', methods=['POST'])
def upload_image():
    if 'file' not in request.files:
        return jsonify(error="No file part"), 400
    file = request.files['file']
    if file.filename == '':
        return jsonify(error="No selected file"), 400
    filename = secure_filename(file.filename)
    filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
    file.save(filepath)
    
    # 读取图像并转换颜色空间
    image = cv2.imread(filepath)  # 补全：读取图像文件
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)  # 补全：BGR转RGB

    # 裁剪处理
    crop_box_coords = request.form.get('cropBoxCoords')
    if crop_box_coords:
        x, y, width, height = [int(coord) for coord in crop_box_coords.split(',')]
        image = image[y:y+height, x:x+width]  # 补全：裁剪图像区域

    palette = extract_colors(image)
    palette_for_js = ["#%02x%02x%02x" % (int(color[0]), int(color[1]), int(color[2])) for color in palette]
    return jsonify(palette_for_js)

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True, port=5001)